package org.zhb.sys.shiro.role.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.zhb.sys.shiro.role.repository.RoleRepository;
import org.zhb.sys.shiro.role.service.RoleService;

import org.zhb.sys.shiro.model.Role;

/**
 * Role服务实现。
 * 
 * @author zhb
 *
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;

	@Override
	public Role insert(Role role) {
		return roleRepository.saveAndFlush(role);
	}

	@Override
	public Role selectRoleById(String id) {
		return roleRepository.findOne(id);
	}

	@Override
	public Role update(Role role) {
		return roleRepository.saveAndFlush(role);
	}

	@Override
	public void delete(String id) {
		roleRepository.delete(id);
	}

	@Override
	public void saveBatch(List<Role> roles) {
		roleRepository.save(roles);
	}

	@Override
	public Page<Role> selectModelByCondition(Role role, PageRequest pageRequest) {
		Specification<Role> specification = getWhereClause(role);
		Page<Role> roleList = roleRepository.findAll(specification, pageRequest);
		return roleList;
	}

	/**
	 * 条件拼接
	 * 
	 * @param role
	 * @return
	 */
	private Specification<Role> getWhereClause(Role role) {
		return new Specification<Role>() {
			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		};
	}

	@Override
	public Page<Role> selectModelByCondition(PageRequest pageRequest) {
		return roleRepository.findAll(pageRequest);
	}

	@Override
	public List<Role> selectAllRole() {
		return roleRepository.findAll();
	}
}